package com.godGuang.system.config;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName EmailConfig
 * @Author 董曙榕
 * @Date 2024/1/8 17:23
 * @Version 1.0
 * @Description TODO
 **/

/**
 * 邮箱配置
 */
@Slf4j
@Component
public class EmailConfig {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queuesToDeclare = {@Queue(name = "send_sms_queue_email")})
    public void mqSendMessage(String email, Channel channel, Message message) {

        log.info("邮箱消费者队列接收到消息，消息内容：{}", email);
        // 获取消息队列ID
        String messageId = message.getMessageProperties().getMessageId();

        Long smsKey = redisTemplate.opsForSet().add("send_sms_queue_email", messageId);
        if (smsKey != null && smsKey == 1) {
            try {
                MailUtils mailUtils = new MailUtils();
                int code = RandomUtils.nextInt(0, 9999);
                mailUtils.sendSimpleEmail(email, "修改密码", "验证码为：" + code + ",验证码5分钟有效");
                System.out.println(code);

                redisTemplate.opsForValue().set(email, code + "", 5, TimeUnit.MINUTES);

                String s = redisTemplate.opsForValue().get(email);
                System.out.println("222222222222     " + s);
                // 确认消息消费成功
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                log.info("监听消息队列，消息内容: {}，监听成功...", email);
            } catch (Exception e) {
                redisTemplate.opsForSet().remove("send_sms_queue_email", messageId);
                log.error("消息内容:", e);
            }
        } else {
            log.info("监听消息队列，消息内容: {}，监听失败...", email);
            try {
                // 拒绝消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                // 处理IO异常
                log.error("消息拒绝失败", ex);
            }
        }
    }

}
